#! usr/bin/env python3
# -*- coding: utf-8 -*-

"""
手写识别主程序。

启动server.py，则同一局域网内设备可以通过网页访问本机，获取手写输入的网页，在该网页上
手写数字，上传回本机，将数据保存在工作目录下，名为sample.txt和sample.png。本程序每隔
一段时间检测一次sample.txt文件，若发现文件被修改，则读取文件，解析出笔迹数据，进行识，
别，并输出识别结果。

下面这两个函数其实写得不好。

2019-2-14
Happy Valentin's day !!!
"""

import time
import os
import trajectory_preprocess as pre
import img_preprocess as img_pre
import knn_recog2 as recog


F_NAME_TRA = r'sample.txt'  # file name of trajectory
F_NAME_IMG = r'sample.png'  # flle name of image


def recog_digit():
    """:param preprocess_func, the func used to convert the text data to ndarray."""
    with open(F_NAME_TRA) as f:
        line = f.readline()
        p.load(line)
        arr = p.export()

        digit = recog.predict(arr)
        digit = digit[0]

    return digit


def print_digit(digit):
    global p
    CHAR = ' .'

    img = img_pre.pre_process(F_NAME_IMG)
    arr = img_pre.get_array(img).reshape(img_pre.IMG_SIZE)
    tra = p.export()[0] / 3.125
    tra = tra.reshape([8, 2])
    tra[:, 1] = -tra[:, 1]
    tra[:, 1] += 32
    print("tra @ main: %s" % str(tra))

    for y in range(img_pre.IMG_SIZE[1]):
        # draw png image
        for x in range(img_pre.IMG_SIZE[0]):
            if arr[y][x] == 1:
                print(' %i' % digit, end='')
            else:
                print(CHAR, end='')

        # draw resampled trajectory points
        print('   ', end='')
        for x in range(img_pre.IMG_SIZE[0]):
            def match_pos():
                for p in tra:
                    if p[0]-1 <= x <= p[0]+1 and p[1]-1 <= y <= p[1]+1:
                        raise IOError
            try:
                match_pos()
                print(CHAR, end='')
            except IOError:
                print(('%i' % digit) * 2, end='')
        print()


p = pre.PreProcessor()

print("main2 All ready.")
if __name__ == '__main__':
    total = 0
    lastModifiedTime = os.path.getmtime(F_NAME_TRA)
    while True:
        time.sleep(1)

        t = os.path.getmtime(F_NAME_TRA)
        if t > lastModifiedTime:
            # if True:
            lastModifiedTime = t
            total += 1

            try:
                digit = recog_digit()
                print_digit(digit)
            except ValueError:
                print("Nothing matters, it is just a bug occurred. ")
            print('total: %i' % total)


